import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { Response, Request } from 'express';

// 定义错误响应类型
interface ErrorResponse {
  success: boolean;
  statusCode: number;
  message: any;
  timestamp: string;
  path: string;
  error?: string;
  stack?: string[];
}

/**
 * HTTP 异常过滤器
 */
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(HttpExceptionFilter.name);

  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    let message: string | object;
    let error: string | undefined;

    if (exception instanceof HttpException) {
      message = exception.getResponse();
      if (typeof message === 'object') {
        message = (message as any)?.message;
      }
    } else if (exception instanceof Error) {
      // 开发环境返回详细错误信息
      const isDevelopment = process.env.NODE_ENV !== 'production';
      message = isDevelopment ? exception.message : 'Internal server error';
      error = isDevelopment ? exception.name : undefined;
    } else {
      message = 'Internal server error';
    }

    // 记录错误详情到控制台
    if (status === (HttpStatus.INTERNAL_SERVER_ERROR as number)) {
      this.logger.error(
        `内部服务器错误: ${request.method} ${request.url}`,
        exception instanceof Error ? exception.stack : String(exception),
      );
    } else {
      this.logger.warn(
        `请求异常: ${request.method} ${request.url} - ${JSON.stringify(message)}`,
      );
      this.logger.debug(`请求 Headers: ${JSON.stringify(request.headers)}`);
      this.logger.debug(`请求 Body: ${JSON.stringify(request.body)}`);
    }

    // 构建响应
    const errorResponse: ErrorResponse = {
      success: false,
      statusCode: status,
      message: message as string,
      timestamp: new Date().toISOString(),
      path: request.url,
    };

    // 开发环境添加额外的调试信息
    if (process.env.NODE_ENV !== 'production' && exception instanceof Error) {
      errorResponse.error = error;
      errorResponse.stack = exception.stack
        ? exception.stack.split('\n').slice(0, 5)
        : undefined;
    }

    response.status(status).json(errorResponse);
  }
}
